package books.storage.eao;

import java.util.Date;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import books.storage.entity.BookEntity;
 
@LocalBean
@Stateless
public class BookManagerEao implements IBookManagerEao {
 
    @PersistenceContext
    EntityManager em;
 
    public BookManagerEao() { }
 
    public BookManagerEao(EntityManager em) { this.em = em; } // for unit test
	
	public BookEntity searchBookByReference(String _ISBN) {
		return (BookEntity) em.createQuery("SELECT be FROM BookEntity be WHERE be.isbn = :ref")
				.setParameter("ref", _ISBN).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	public List<BookEntity> searchBookByName(String _title) {
		return em.createQuery("SELECT be FROM BookEntity be WHERE be.title like :title")
				.setParameter("title", "%" + _title + "%").getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<BookEntity> searchBookByAuthor(String _authorName) {
		System.out.println("SELECT be FROM BookEntity be WHERE be.author.name like :authorName");
		return em.createQuery("SELECT be FROM BookEntity be WHERE be.author.name like :authorName")
				.setParameter("authorName", "%" + _authorName + "%").getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<BookEntity> searchBookBetweenEditionDates(Date _first,
			Date _second) {
		return em.createQuery("SELECT be FROM BookEntity be WHERE be.editionDate between :firstDate and :secondDate")
				.setParameter("firstDate", _first).setParameter("secondDate", _second).getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<BookEntity> searchBookByLiteraryGenre(String _genreName) {
		return em.createQuery("SELECT be FROM BookEntity be WHERE be.literaryGenre.wording = :genreName")
				.setParameter("genreName", _genreName).getResultList();
	}
 
}
